package org.jiuling.request.http.handle;

import org.jiuling.request.exception.RequestRuntimeException;
import org.jiuling.request.http.HttpRequest;
import org.jiuling.request.http.core.HttpRequestCore;
import org.jiuling.request.http.model.HttpResponse;
import org.jiuling.request.http.trustmanager.DefaultTrustManager;

import javax.net.ssl.*;
import java.io.IOException;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * https请求处理
 * @author 紫灵
 * @date 2024年08月28日 20时58分13秒
 */
public class HttpsRequestHandle extends HttpRequestCore implements HttpRequest {

    public HttpsRequestHandle(URI uri) {
        super(uri);
    }

    @Override
    public HttpResponse send() throws IOException {
        try {
            SSLContext sslContext = SSLContext.getInstance(super.sslProtocol.getCode());

            // SSLContext初始化
            sslContext.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());

            // 开启HTTPS连接
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) super.openConnection();

            // 获取socker工厂
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            // 设置socket工厂
            httpsURLConnection.setSSLSocketFactory(sslSocketFactory);

            // 连接
            super.connect(httpsURLConnection);

            HttpResponse httpResponse = super.packageHttpResponse(httpsURLConnection);
            httpsURLConnection.disconnect();
            ResponseHandle.errorHandle(httpResponse);
            return httpResponse;
        } catch (NoSuchAlgorithmException e) {
            throw new RequestRuntimeException("SSL算法不正确！");
        } catch (KeyManagementException e) {
            throw new RequestRuntimeException("SSL密钥不正确！");
        }
    }
}
